package com.beta.pay.yeepay.core;

import com.alibaba.fastjson.JSON;
import com.beta.pay.yeepay.exception.YeepayException;
import com.beta.pay.yeepay.utils.ZGTUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by vector on 2016/11/30.
 */
public abstract class Component {

    protected final Logger logger = LoggerFactory.getLogger(getClass());

    protected Yeepay yeepay;

    public Component(Yeepay yeepay) {
        this.yeepay = yeepay;
    }

    protected Map<String, String> fetchData(String url, Map<String, String> paramMap, String[] requestHmacOrder, String[] responseHmacOrder) {

        logger.info("易宝支付 - {} ==> 请求开始：param = {}", getComponentName(), JSON.toJSONString(paramMap));

        // 第一步 生成密文data
        String data	= ZGTUtils.buildData(paramMap, requestHmacOrder);

        Map<String, String> responseMap = ZGTUtils.httpPost(url, data);
        logger.info("易宝支付 - {} ==> 请求结束: response = {}", getComponentName(), JSON.toJSONString(responseMap));

        // 第三步 判断请求是否成功，
        if (responseMap.containsKey("code")) {
            logger.error("易宝支付 - {} ==> 请求失败: response = {}", getComponentName(), JSON.toJSONString(responseMap));
            throw new YeepayException(responseMap.get("code"), responseMap.get("msg"));
        }

        // 第四步 解密同步响应密文data，获取明文参数
        String responseData = responseMap.get("data");
        return decodeData(responseData, responseHmacOrder);
    }

    protected Map<String, String> decodeData(String data, String[] hmacOrder) {
//        logger.info("易宝支付 - {} ==> 解码数据: encryptData = {}", getComponentName(), data);
        if (StringUtils.isEmpty(data)) {
            return new HashMap<>();
        }

        Map<String, String> decryptData = ZGTUtils.decryptData(data);
        logger.info("易宝支付 - {} ==> 数据解码: decryptData = {}", getComponentName(), JSON.toJSONString(decryptData));

        // code=1时，表示接口处理成功
        if (!"1".equals(decryptData.get("code"))) {
            logger.error("易宝支付 - {} ==> 接口处理失败: error = {}", getComponentName(), JSON.toJSONString(decryptData));
            throw new YeepayException(decryptData.get("code"), decryptData.get("msg"));
        }

        // hmac签名验证
        if (ArrayUtils.isNotEmpty(hmacOrder)) {
            if (!ZGTUtils.checkHmac(decryptData, hmacOrder)) {
                logger.error("易宝支付 - {} ==> hmac校验失败: error = {}", getComponentName(), JSON.toJSONString(decryptData));
                throw new YeepayException(decryptData.get("code"), "hmac校验失败");
            }
        }
        return decryptData;
    }

    abstract protected String getComponentName();

}
